package com.zxshhy.filters;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 酷点后台的filter
 *
 * @author Janus
 */
@SuppressWarnings("DuplicatedCode")
@Slf4j
@Component
public class BusinessAdminFilter implements GatewayFilterFactory<BusinessAdminFilter.Config> {
    private static final String TOKEN_KEY = "X-BUSINESS-TOKEN";
//    @Autowired
//    private JwtProperties jwtProperties;
//    @Autowired
//    private MchUserTokenService mchUserTokenService;
//    @Autowired
//    private SkipUrlHandler skipUrlHandler;


    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        if (skipUrlHandler.skipUrl(exchange)) {
//            log.info("url: {}", exchange.getRequest().getURI());
//            return chain.filter(exchange);
//        }
//        String token = AuthHelper.getToken(TOKEN_KEY, exchange.getRequest());
//        JwtUserInfo jwtInfo = AuthHelper.parseToken(token);
//        log.info("url: {}, jwnInfo: {}", exchange.getRequest().getURI(), jwtInfo);
//        boolean b = AuthHelper.checkJwt(jwtInfo, JwtConstants.Scope.BUSINESS, jwtProperties.getVersion());
//        if (!b) {
//            return AuthHelper.authFail(exchange, ApiResult.create(ResponseCode.INVAILD_TOKEN));
//        }
//
//        Long businessId = jwtInfo.getBusinessId();
//        Integer userId = Integer.parseInt(jwtInfo.getUserId());
//        boolean valid = mchUserTokenService.containsToken(businessId, userId, token);
//        if (!valid) {
//            log.info("token已登出: token:{}, info: {}", token, jwtInfo);
//            return AuthHelper.authFail(exchange, ApiResult.create(ResponseCode.INVAILD_TOKEN));
//        }

        ServerWebExchange newExchange = doRun(exchange);
        return chain.filter(newExchange);
    }

    private ServerWebExchange doRun(ServerWebExchange exchange) {
        ServerHttpRequest.Builder requestBuilder = exchange.getRequest().mutate();
        // 旧逻辑
        requestBuilder.header("user_zhuxueshi", RandomStringUtils.random(10));
        return exchange.mutate().request(requestBuilder.build()).build();
    }

    @Override
    public Config newConfig() {
        return new Config();
    }

    @Override
    public GatewayFilter apply(Config config) {
        return this::filter;
    }

    public static class Config {
        public Config() {
        }
    }
}

